<template>
  <Cascader v-bind="$attrs" :options="options" @change="handleChange" />
</template>

<script>
import { defineComponent, ref, watchEffect } from 'vue'
import { Cascader } from 'element-ui'
import { isFunction, isArray, get } from 'lodash-es'

export default defineComponent({
  name: 'ApiCascader',
  components: { Cascader },
  props: {
    api: {
      type: Function,
      required: true
    },
    params: {
      type: Object,
      default: () => {}
    },
    resultField: {
      type: String,
      default: ''
    },
    // 是否立即请求
    immediate: {
      type: Boolean,
      default: true
    }
  },
  emits: ['options-change'],
  setup(props, { emit }) {
    const options = ref([])

    watchEffect(() => {
      props.immediate && fetch()
    })

    async function fetch() {
      const { api, params } = props
      if (!api && !isFunction(api)) return
      options.value = []
      const res = await api(params)
      if (isArray(res)) {
        options.value = res
      } else {
        props.resultField && (options.value = get(res, props.resultField) || [])
      }
    }

    function handleChange(e) {
      emit('options-change', e)
    }

    return {
      options,
      handleChange
    }
  }
})
</script>
